package com.noodles.mall.util;

import cn.hutool.core.io.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Component
public class Upload {
    @Value("${sys.fileUploadPath}")
    private String parentPath;

    /** 保存文件 **/
    public String save(MultipartFile file,String dir){
        System.out.println("Upload: save");
        System.out.println("file: " + file);
        System.out.println("dir: " + dir);
        if(dir.startsWith("/")) dir=dir.replace("/","");
        try {
            // 图片后缀名
            String suf = FileUtil.getSuffix(file.getOriginalFilename());
            //新图片名
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suf;
            File dirFile = new File(parentPath,dir);
            System.out.println("parentPath: "+parentPath);
            if(!dirFile.exists()) dirFile.mkdirs();
            //写入文件
            FileUtil.writeBytes(file.getBytes(), new File(dirFile,fileName));
            return dir+"/"+fileName;
        } catch (Exception e) {
            return null;
        }
    }

    /** 删除文件 **/
    public boolean delete(String url){
        System.out.println("Upload: delete");
        System.out.println("url: " + url);
        return new File(parentPath,url).delete();
    }
}
